<script setup lang="ts">
import { CaretRightOutlined } from '@ant-design/icons-vue'
import { onMounted, ref } from 'vue'
import { getCreateTimeList, getPictureListByCreateTime } from '@/api/pictureController.ts'

const activeMainKey = ref<string[]>([]) // 只存储主面板的key（日期）
const activeSubKey = ref<Record<string, string[]>>({}) // 存储子面板的key，格式：{ 日期: [fieldId数组] }
const createTimeList = ref<string[]>([])
const pictureData = ref<Record<string, Record<number, string[]>>>({})

const getTimeList = async () => {
  const res = await getCreateTimeList()
  createTimeList.value = res.data.data ?? []

  // 初始化所有子面板状态为空数组
  createTimeList.value.forEach((time) => {
    if (!activeSubKey.value[time]) {
      activeSubKey.value[time] = []
    }
  })
}

const getPictureList = async (createTime: string) => {
  try {
    const res = await getPictureListByCreateTime({
      createTime: createTime + 'T00:00:00',
    })

    if (res.data.code === 0 && res.data.data) {
      pictureData.value[createTime] = res.data.data
      console.log('获取图片数据成功:', res.data.data)
    }
  } catch (error) {
    console.error('获取图片数据失败:', error)
  }
}

const changeMainPanel = (keys: string[]) => {
  console.log('切换主面板:', keys)
  activeMainKey.value = keys

  // 当主面板展开时加载数据
  if (keys.length > 0) {
    const currentKey = keys[0]
    if (!pictureData.value[currentKey]) {
      getPictureList(currentKey)
    }
  }
}

const changeSubPanel = (parentKey: string, keys: string[]) => {
  console.log(`切换子面板 ${parentKey}:`, keys)
  // 确保父key存在
  if (!activeSubKey.value[parentKey]) {
    activeSubKey.value[parentKey] = []
  }
  // 只存储有效的fieldId，避免undefined和空字符串
  const validKeys = keys.filter((key) => key && key.trim() !== '' && key !== 'undefined')
  activeSubKey.value[parentKey] = validKeys
}

onMounted(() => {
  getTimeList()
})
</script>

<template>
  <div class="picture-detail-page">
    <a-collapse
      v-model:activeKey="activeMainKey"
      :bordered="false"
      style="background: rgb(255, 255, 255)"
      @change="changeMainPanel"
    >
      <template #expandIcon="{ isActive }">
        <caret-right-outlined :rotate="isActive ? 90 : 0" />
      </template>

      <!-- 外层折叠面板：按日期分组 -->
      <a-collapse-panel
        v-for="createTime of createTimeList"
        :key="createTime"
        :header="createTime"
        class="outer-collapse-panel"
      >
        <!-- 内层折叠面板：按fieldId分组 -->
        <a-collapse
          v-model:activeKey="activeSubKey[createTime]"
          :bordered="false"
          style="margin-top: 8px"
          @change="(keys) => changeSubPanel(createTime, keys)"
        >
          <template #expandIcon="{ isActive }">
            <caret-right-outlined :rotate="isActive ? 90 : 0" />
          </template>

          <!-- 检查是否有该日期的图片数据 -->
          <template v-if="pictureData[createTime]">
            <a-collapse-panel
              v-for="(imageUrls, fieldId) in pictureData[createTime]"
              :key="fieldId.toString()"
              :header="`农田 ${fieldId}`"
              class="inner-collapse-panel"
            >
              <!-- 图片列表 -->
              <div class="image-grid">
                <a-image
                  v-for="(url, index) in imageUrls"
                  :key="`${fieldId}-${index}`"
                  :src="url"
                  :alt="`农田${fieldId}图片${index + 1}`"
                  :width="200"
                  :height="200"
                  fit="cover"
                  class="image-item"
                  preview
                />
              </div>
            </a-collapse-panel>
          </template>

          <!-- 加载状态 -->
          <template v-else-if="activeMainKey.includes(createTime)">
            <div class="loading">
              <a-spin size="small" />
              <span style="margin-left: 8px">加载中...</span>
            </div>
          </template>

          <!-- 暂无数据状态 -->
          <template v-else>
            <div class="no-data">点击展开查看图片</div>
          </template>
        </a-collapse>
      </a-collapse-panel>
    </a-collapse>
  </div>
</template>

<style scoped>
.picture-detail-page {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.outer-collapse-panel {
  background: #ffffff !important;
  border-radius: 8px !important;
  margin-bottom: 16px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.inner-collapse-panel {
  background: #f7f7f7 !important;
  border-radius: 6px !important;
  margin-bottom: 8px !important;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px;
}

.image-item {
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.image-item:hover {
  transform: scale(1.02);
}

.loading {
  padding: 24px;
  text-align: center;
  color: #666;
}

.no-data {
  padding: 24px;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>
